<template>
    <div class="article-edit" v-loading.fullscreen.lock="fullscreenLoading">
        <el-card class="!border-none" shadow="never">
            <el-page-header
                :content="route.query.id ? '编辑证书' : '添加证书'"
                @back="$router.back()"
            />
        </el-card>
        <el-card class="mt-4 !border-none" shadow="never">
            <el-form
                class="ls-form"
                label-width="100px"
                :model="formData"
                :rules="rules"
                ref="formRef"
            >
                <div class="xl:flex">
                    <div>
                        <el-form-item label="证书名称" prop="name">
                            <div class="w-[245px]">
                                <el-input v-model="formData.name" placeholder="请输入证书名称" />
                            </div>
                        </el-form-item>

                        <el-form-item label="证书图片" prop="images" required>
                            <div>
                                <div class="up-list">
                                    <div
                                        class="up-body"
                                        v-for="(item, index) in formData.zs_imgs"
                                        :key="index"
                                    >
                                        <div class="up-icon" @click.stop="colse(index)">
                                            <el-icon color="#303133" :size="22">
                                                <CircleCloseFilled />
                                            </el-icon>
                                        </div>
                                        <img :src="item" class="avatar" />
                                        <div class="up-cz">
                                            <span @click.stop="seeImg(item)">查看</span>
                                        </div>
                                    </div>

                                    <el-upload
                                        class="avatar-uploader"
                                        ref="uploadRefs"
                                        :on-change="onChange"
                                        :auto-upload="false"
                                        :show-file-list="false"
                                        v-if="formData.zs_imgs.length < 9"
                                    >
                                        <div class="up-box">
                                            <el-icon color="#606266" :size="20">
                                                <Plus />
                                            </el-icon>
                                        </div>
                                    </el-upload>
                                </div>
                            </div>
                        </el-form-item>

                        <el-form-item label="证书类型" prop="type">
                            <el-select v-model="formData.type" placeholder="请选择证书类型">
                                <el-option label="白名单" :value="0" />
                                <el-option label="综合素质测评" :value="1" />
                            </el-select>
                        </el-form-item>

                        <!-- 证书类型 == 综合素质测评，显示此内容 -->
                        <div v-if="formData.type == 1">
                            <el-form-item label="证书分类" prop="t_id">
                                <el-select v-model="formData.t_id" placeholder="请选择证书分类">
                                    <el-option
                                        v-for="item in types"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    />
                                </el-select>
                            </el-form-item>

                            <el-form-item label="价格" prop="price">
                                <div class="w-[245px]">
                                    <el-input v-model="formData.price" placeholder="请输入价格" />
                                </div>
                            </el-form-item>

                            <el-form-item label="操作视频" prop="video">
                                <div>
                                    <el-upload
                                        class="avatar-uploader"
                                        ref="uploadRefs"
                                        :multiple="false"
                                        :limit="1"
                                        :show-file-list="false"
                                        action=""
                                        :auto-upload="false"
                                        :on-change="onChangeVideo"
                                        accept="mp4"
                                    >
                                        <el-button type="primary">上传操作视频</el-button>
                                    </el-upload>

                                    <div style="width: 600px" v-if="formData.video">
                                        <vue3VideoPlay
                                            width="600px"
                                            title="操作视频"
                                            type="m3u8"
                                            :src="formData.video_url"
                                            :poster="formData.fm_url"
                                        />
                                    </div>
                                </div>
                            </el-form-item>

                            <el-form-item label="视频封面图" prop="fm_image">
                                <div>
                                    <el-upload
                                        class="avatar-uploader"
                                        ref="uploadRefs"
                                        :on-change="onChangePoster"
                                        :auto-upload="false"
                                        :show-file-list="false"
                                        v-loading="loadingFmt"
                                    >
                                        <div class="up-box" v-if="formData.fm_url == ''">
                                            <el-icon color="#606266" :size="20">
                                                <Plus />
                                            </el-icon>
                                        </div>
                                        <img v-else :src="formData.fm_url" class="avatar" />
                                    </el-upload>
                                </div>
                            </el-form-item>
                        </div>

                        <el-form-item label="适合学段" prop="study_section">
                            <el-checkbox-group v-model="formData.study_section">
                                <el-checkbox label="1">小学</el-checkbox>
                                <el-checkbox label="2">初中</el-checkbox>
                                <el-checkbox label="3">高中</el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>

                        <el-form-item label="是否热门" prop="is_hot" required>
                            <el-radio-group v-model="formData.is_hot">
                                <el-radio :label="1">是</el-radio>
                                <el-radio :label="2">否</el-radio>
                            </el-radio-group>
                        </el-form-item>

                        <el-form-item label="详情介绍" prop="content">
                            <div style="border: 1px solid #ccc; maxwidth: 600px">
                                <!-- 工具栏 -->
                                <Toolbar
                                    style="border-bottom: 1px solid #ccc"
                                    :editor="editorRef"
                                    :defaultConfig="toolbarConfig"
                                    :mode="'content'"
                                />
                                <!-- 内容部分 -->
                                <Editor
                                    style="height: 450px; overflow-y: hidden"
                                    v-model="formData.content"
                                    :defaultConfig="editorConfig"
                                    :mode="'content'"
                                    @onCreated="handleCreated"
                                    @onChange="handleChange"
                                />
                            </div>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </el-card>
        <footer-btns>
            <el-button type="primary" @click="submitData">保存</el-button>
        </footer-btns>
        <!-- 查看图片弹框 -->
        <el-dialog v-model="dialogVisible" title="查看" width="35%" :show-close="false">
            <img
                :src="formData.zs_image"
                alt="加载失败"
                style="width: 90%; display: block; margin: 0 auto"
            />
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="dialogVisible = false"> 关闭 </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="articleListsEdit">
import { ref } from 'vue'
import { fpFile, fpRichImg, fpVideo, videoPlay } from '@/api/fpUpLoad'
import { certificateDetail, certificateEdit, classification } from '@/api/certificate'
import useMultipleTabs from '@/hooks/useMultipleTabs'
import type { FormInstance, FormRules } from 'element-plus'
import feedback from '@/utils/feedback'

// 富文本---这四行必须全部引入！！！！！
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, shallowRef } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import type { IEditorConfig, IToolbarConfig } from '@wangeditor/core'

const fullscreenLoading = ref(false)
const { removeTab } = useMultipleTabs()
const route = useRoute()
const router = useRouter()
const loading = ref()
const loadingFmt = ref()
const types = ref([])

const formRef = shallowRef<FormInstance>()
const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入分类名称', trigger: ['blur', 'change'] }],
    type: [{ required: true, message: '请选择证书类型', trigger: ['blur', 'change'] }],
    images: [{ required: true, message: '请上传证书图片', trigger: ['blur', 'change'] }],
    t_id: [{ required: true, message: '请选择证书分类', trigger: ['blur', 'change'] }],
    price: [{ required: true, message: '请输入价格', trigger: ['blur', 'change'] }],
    study_section: [{ required: true, message: '请选择适合学段', trigger: ['blur', 'change'] }],
    video: [{ required: true, message: '请上传操作视频', trigger: ['blur', 'change'] }],
    fm_image: [
        {
            required: true,
            message: '请上传视频封面图',
            trigger: ['blur', 'change']
        }
    ],
    content: [
        {
            required: true,
            message: '请输入证书详情介绍',
            trigger: ['blur', 'change']
        }
    ]
})

// 公用数据
const formData = reactive({
    id: route.query.id,
    // 接口字段
    name: '',
    type: 1,
    images: '',
    t_id: '',
    price: '',
    video: '',
    fm_image: '',
    fm_url: '',
    content: '',
    is_hot: 1,
    study_section: [],

    // 图片  视频
    zs_imgs: [],
    zs_path: [],
    zs_image: '',

    video_url: ''
})

// 上传证书图片
const dialogVisible = ref(false)
const listArr = ref([])
// 选择证书图片
const onChange = (file: any) => {
    //   console.log("文件信息:", file);
    listArr.value = []
    // 假设1024一片，可根据实际来进行，也可以调接口进行
    const count = Math.ceil(file.size / 1024 / 1024 / 5)
    // 拿文件后缀
    const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
    const chunkid = generateUUID()
    for (let i = 0; i < count; i++) {
        const item = new FormData()
        item.append('chunkindex', i) //当前是第几片
        item.append('chunkcount', count) //分片的总数量
        item.append('files', file.raw.slice(i * 1024 * 1024 * 5, (i + 1) * 1024 * 1024 * 5)) //文件流数据
        item.append('extension', suffix) //文件的后缀
        item.append('name', file.name) //文件名
        item.append('size', file.size) //文件大小
        item.append('mime', file.raw.type) //文件的mime类型
        item.append('chunkid', chunkid) //文件uid，选的每个文件不一样，做区分（不是每个分片的）
        item.append('key', 'iNWxBywRQMn3bXZ8E5OGszoAVIjL9P') //上传接口需要的key，不是固定写死的，根据后端修改调整
        listArr.value.push(item)
    }
    loading.value = true
    file_up('zs')
}

// 选择视频封面片
const onChangePoster = (file: any) => {
    //   console.log("文件信息:", file);
    listArr.value = []
    // 假设1024一片，可根据实际来进行，也可以调接口进行
    const count = Math.ceil(file.size / 1024 / 1024 / 5)
    // 拿文件后缀
    const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
    const chunkid = generateUUID()
    for (let i = 0; i < count; i++) {
        const item = new FormData()
        item.append('chunkindex', i) //当前是第几片
        item.append('chunkcount', count) //分片的总数量
        item.append('files', file.raw.slice(i * 1024 * 1024 * 5, (i + 1) * 1024 * 1024 * 5)) //文件流数据
        item.append('extension', suffix) //文件的后缀
        item.append('name', file.name) //文件名
        item.append('size', file.size) //文件大小
        item.append('mime', file.raw.type) //文件的mime类型
        item.append('chunkid', chunkid) //文件uid，选的每个文件不一样，做区分（不是每个分片的）
        item.append('key', 'iNWxBywRQMn3bXZ8E5OGszoAVIjL9P') //上传接口需要的key，不是固定写死的，根据后端修改调整
        listArr.value.push(item)
    }
    loadingFmt.value = true
    file_up('fmt')
}

// 获取uuid
const generateUUID = () => {
    let d = new Date().getTime()
    if (window.performance && typeof window.performance.now === 'function') {
        d += performance.now()
    }
    const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        const r = (d + Math.random() * 16) % 16 | 0
        d = Math.floor(d / 16)
        return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
    })
    return uuid
}

// 走上传接口
const file_up = async (type: any) => {
    let video_index = 0
    for (const v of listArr.value) {
        video_index++
        const res = await fpFile(v)
        if (video_index == listArr.value.length) {
            if (type == 'zs') {
                formData.zs_imgs.push(res.show_url)
                formData.zs_path.push(res.save_url)
            } else {
                formData.fm_url = res.show_url
                formData.fm_image = res.save_url
            }
        }
    }
    loading.value = false
    loadingFmt.value = false
}

// 视频播放插件
// const play_video = ref<any>(null);
// const options = reactive({
//   width: "100%", //播放器高度
//   height: "100%", //播放器高度
//   color: "#409eff", //主题色
//   title: "", //视频名称
//   src: "", //视频源
//   type: "m3u8",
//   muted: false, //静音
//   webFullScreen: false,
//   speedRate: ["0.75", "1.0", "1.25", "1.5", "2.0"], //播放倍速
//   autoPlay: false, //自动播放
//   loop: false, //循环播放
//   mirror: false, //镜像画面
//   ligthOff: false, //关灯模式
//   volume: 0.3, //默认音量大小
//   control: true, //是否显示控制器
// });

// 选择视频文件
const onChangeVideo = (file: any) => {
    //   console.log("文件信息:", file);
    listArr.value = []
    if (file.name.indexOf('mp4') == -1) {
        return feedback.msgError(`只能上传MP4格式的视频`)
    }

    // 假设1024一片，可根据实际来进行，也可以调接口进行
    const count = Math.ceil(file.size / 1024 / 1024 / 1)
    const chunkid = generateUUID()

    for (let i = 0; i < count; i++) {
        const item = new FormData()
        item.append('chunkindex', i) //当前是第几片
        item.append('chunkcount', count) //分片的总数量
        item.append('files', file.raw.slice(i * 1024 * 1024 * 1, (i + 1) * 1024 * 1024 * 1)) //文件流数据
        item.append('extension', 'mp4') //文件的后缀
        item.append('name', file.name) //文件名
        item.append('size', file.size) //文件大小
        item.append('mime', file.raw.type) //文件的mime类型
        item.append('chunkid', chunkid) //文件uid，选的每个文件不一样，做区分（不是每个分片的）
        item.append('key', 'iNWxBywRQMn3bXZ8E5OGszoAVIjL9P') //上传接口需要的key，不是固定写死的，根据后端修改调整
        listArr.value.push(item)
        video_up()
    }
}

// 视频上传
const video_up = async () => {
    // 页面全屏加载效果
    fullscreenLoading.value = true
    let video_index = 0
    //   循环请求接口，上传视频，只有最后一个是需要的数据
    for (const v of listArr.value) {
        video_index++
        const res = await fpVideo(v)
        // console.log("走上传视频接口", res.save_url);
        // 到最后一个的时候，添加页面效果
        if (video_index == listArr.value.length) {
            fullscreenLoading.value = false
            formData.video = res.save_url
            formData.video_url = res.show_url
            feedback.msgSuccess(`上传成功`)
        }
    }
}

// 获取视频
const getVideo = async () => {
    const data = await videoPlay({
        path: formData.video,
        key: 'iNWxBywRQMn3bXZ8E5OGszoAVIjL9P'
    })
    formData.video_url = data.show_url
}

// 删除证书图片
const colse = async (index: number) => {
    formData.zs_path.splice(index, 1)
    formData.zs_imgs.splice(index, 1)
}

// 查看图片
const seeImg = async (item: any) => {
    dialogVisible.value = true
    formData.zs_image = item
}

// 获取详情
const getInfo = async () => {
    const data = await certificateDetail({
        id: route.query.id
    })
    Object.keys(formData).forEach((key) => {
        //@ts-ignore
        formData[key] = data[key]
        // 获取资质转换数据格式
        formData.zs_imgs = data.images_url
        formData.zs_path = data.images
        formData.fm_image = data.fm_image
        formData.fm_url = data.fm_image_url
        formData.study_section = data.study_section.split(',')
    })
    getVideo()
}

//保存添加
const submitData = async () => {
    formData.images = formData.zs_path.toString()
    formData.study_section = formData.study_section.toString()
    // 表单判断,走接口
    await formRef.value?.validate()
    if (formData.content == '<p><br></p>') {
        return feedback.msgError(`请输入证书详情介绍`)
    }
    await certificateEdit(formData)
    removeTab()
    router.back()
}

// 获取分类
const getbannerinfo = async () => {
    const data = await classification({})
    types.value = data
}
getbannerinfo()
route.query.id && getInfo()

//富文本编译==========================================================
const emits = defineEmits(['getHtmlVal'])
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 工具栏配置
const toolbarConfig: Partial<IToolbarConfig> = {
    // 用于去掉不需要的工具栏配置
    excludeKeys: [
        'insertVideo', // 去掉插入视频功能
        'fullScreen' // 去掉全屏功能
    ]
}
// 编辑器配置
const editorConfig: Partial<IEditorConfig> = {
    // 最长输入5000字
    maxLength: 5000,
    // 进入页面不自动聚焦
    autoFocus: true,
    MENU_CONF: {}
}
// 上传图片
editorConfig.MENU_CONF['uploadImage'] = {
    async customUpload(file: any, insertFn: any) {
        // upLoadImgVideo("1", file, insertFn);
        const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
        const item = new FormData()
        item.append('file', file)
        item.append('extension', suffix) //文件的后缀
        item.append('key', 'iNWxBywRQMn3bXZ8E5OGszoAVIjL9P') //上传接口需要的key，不是固定写死的，根据后端修改调整
        file_upfw(item, insertFn)
    }
}

// 上传视频
editorConfig.MENU_CONF['uploadVideo'] = {
    async customUpload(file: any, insertFn: any) {
        // upLoadImgVideo("2", file, insertFn);
        const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
        const item = new FormData()
        item.append('file', file)
        item.append('extension', suffix) //文件的后缀
        item.append('key', 'iNWxBywRQMn3bXZ8E5OGszoAVIjL9P') //上传接口需要的key，不是固定写死的，根据后端修改调整
        file_upfw(item, insertFn)
    }
}
// 走接口 - 上传图片、视频
const file_upfw = async (item: any, insertFn: any) => {
    const res = await fpRichImg(item)
    // 把接口返回的数据，添加到编辑器里
    insertFn(res.localdomain_url)
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
    // 查看所有工具栏key
    // console.log(editor.getAllMenuKeys());
}
// 内容改变，获得输入的内容
const handleChange = (editor: any) => {
    emits('getHtmlVal', editor.getHtml())
    formData.content = editor.getHtml()
}
</script>
<style scoped>
/* 上传的样式 */
.up-list {
    display: flex;
}

.up-body {
    position: relative;
    width: 130px;
    height: 130px;
    background-color: #f2f2f2;
    border-radius: 6px;
    margin-right: 10px;
}

.up-box {
    width: 130px;
    height: 130px;
    border-radius: 6px;
    border: 1px dashed #c0c4cc;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.up-cz,
.up-icon {
    display: none;
}

.up-body:hover .up-cz {
    display: block;
    width: 100%;
    position: absolute;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.2);
    color: #ffffff;
    cursor: pointer;
    border-bottom-left-radius: 6px;
    border-bottom-right-radius: 6px;
}

.up-body:hover .up-icon {
    display: block;
    position: absolute;
    top: -10px;
    right: -10px;
}

.up-cz span:nth-of-type(2) {
    margin: 0px 10px;
}

.avatar {
    width: 130px;
    height: 130px;
}

/*添加按钮样式 */
.button-new-tag {
    width: 100px;
    height: 35px;
    background: #4a5dff;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
}

.button-new-tags {
    width: 80px;
    height: 35px;
    background: #4a5dff;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
}

/*输入框长度 */
/deep/.el-input__wrapper {
    width: 245px;
}

/*文本框高度 */
/deep/.el-textarea__inner {
    height: 76px;
}
</style>
